!/bin/bash

host=$1
original=WinXPSandbox
basedir=/opt/cuckoo

if [ "$host" == "" ]
then   
        echo "USAGE: $0 "
        exit 1
fi

if [ "$2" == "" ]
then   
        username="cuckoo"
else   
        username="$2"
fi

if [ "$3" == "" ]
then   
        password="cuckoo"
else   
        password="$3"
fi

echo "Clone virtual machine"
VBoxManage clonevm "$original" --name "$host" --register || exit 1

echo "Create shared folder"
mkdir -p $basedir/shares/$host || exit 1

echo "Clear old settings"
#VBoxManage sharedfolder remove $host --name $original || exit 1
#VBoxManage sharedfolder remove $host --name setup || exit 1
VBoxManage modifyvm $host --nictrace1 off || exit 1

echo "Add new settings"
#VBoxManage sharedfolder add $host --name $host --hostpath $basedir/shares/$host --automount || exit 1
#VBoxManage sharedfolder add $host --name setup --hostpath $basedir/shares/setup --automount --readonly || exit 1
VBoxManage modifyvm $host --nictrace1 on --nictracefile1  $basedir/shares/$host/dump.pcap || exit 1

echo "Start up the virtual machine"
VBoxManage startvm "$host" --type headless || exit 1

echo "Wait until the virtual machine has booted up"
sleep 120

echo "Rename the virtual machine guest OS"
VBoxManage guestcontrol $host execute --username $username --password $password --image 'C:\compname.exe' --wait-exit -- /c $host

echo "Reboot the virtual machine"
VBoxManage guestcontrol $host execute --username $username --password $password --image 'C:\WINDOWS\system32\shutdown.exe'  -- -r -f -t 0

echo "Wait until the virtual machine rebooted"
sleep 120

echo "Create snapshot"
VBoxManage snapshot "$host" take "Initial snapshot from template" --pause || exit 1
VBoxManage controlvm "$host" poweroff || exit 1

echo "Add configuration to cuckoo.conf"
echo "[$host]" >> $basedir/conf/cuckoo.conf
echo "name = $host" >> $basedir/conf/cuckoo.conf
echo "username = $username" >> $basedir/conf/cuckoo.conf
echo "password = $password" >> $basedir/conf/cuckoo.conf
echo "share = shares/$host" >> $basedir/conf/cuckoo.conf
echo >> $basedir/conf/cuckoo.conf
echo >> $basedir/conf/cuckoo.conf

sed -i "/^enabled/s|$|,$host|" $basedir/conf/cuckoo.conf

echo "Done!"
